package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.entity.AllArticle;
import com.woniuxy.entity.DTO.ArticleRankItem;
import com.woniuxy.service.AllArticleService;
import com.woniuxy.mapper.AllArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author nanqiao
* @description 针对表【all_article(内容主表（帖子）)】的数据库操作Service实现
* @createDate 2025-07-22 16:15:34
*/
@Service
public class AllArticleServiceImpl extends ServiceImpl<AllArticleMapper, AllArticle> implements AllArticleService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public AllArticleServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        System.out.println("【DEBUG】RedisTemplate 注入成功: " + redisTemplate); // 新增日志
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取热门文章排行榜（返回 List<AllArticle>，并设置 viewCount）
     * @param topN 排行榜数量
     * @return 文章排行榜列表
     */
    public List<AllArticle> getTopRankedArticles(int topN) {
        System.out.println("【DEBUG】getTopRankedArticles 被调用，topN = " + topN);
        String key = "article:viewCount";
//        在key中添加一条测试数据
        ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
//        zSetOps.add(key, "1", 10);
        Set<ZSetOperations.TypedTuple<Object>> rankedArticles = zSetOps.reverseRangeWithScores(key, 0, topN - 1);
        System.out.println("Data from Redis: " + rankedArticles);
        if (rankedArticles == null || rankedArticles.isEmpty()) {
            System.out.println("【DEBUG】Redis 中没有排行榜数据，key = " + key);
            return new ArrayList<>();
        }
        System.out.println("Data from Redis: " + rankedArticles);
        List<Long> articleIds = new ArrayList<>();
        Map<Long, Long> viewCountMap = new HashMap<>();

        for (ZSetOperations.TypedTuple<Object> tuple : rankedArticles) {
            Object value = tuple.getValue();
            Long articleId;

            if (value instanceof String) {
                articleId = Long.valueOf((String) value);
            } else if (value instanceof Number) {
                articleId = ((Number) value).longValue();
            } else {
                continue;
            }

            articleIds.add(articleId);
            viewCountMap.put(articleId, tuple.getScore().longValue());
        }

        List<AllArticle> articles = listByIds(articleIds);

        // ✅ 设置浏览量到 AllArticle 对象中（和 campus-content 保持一致）
        for (AllArticle article : articles) {
            article.setViewCount(viewCountMap.getOrDefault(article.getId(), 0L));
        }

        return articles;
    }
}
